package com.we.risk.registerchanneldeprecated.basicinfo.dim;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagUserAccount {
    public long uid;
    public Integer register_time;
    public String user_key;
    public int updated_at;

    public static Logger LOG = LoggerFactory.getLogger(TagUserAccount.class);

    public TagUserAccount() {}

    public TagUserAccount(long uid, Integer register_time, String user_key, int updated_at) {
        this.uid = uid;
        this.register_time = register_time;
        this.user_key = user_key;
        this.updated_at = updated_at;
    }

    public static TagUserAccount init(long uid) {
        return new TagUserAccount(uid, 0, "", 0);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        tableEnv.useCatalog("cdh6_hive");
        Table tableRes = tableEnv.sqlQuery(TableUserAccount.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserAccount>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserAccount.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserAccount>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserAccount> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserAccount-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserAccount>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserAccount> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableUserAccount>, String>() {
                                    ValueState<TagUserAccount> userAccountVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userAccountVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserAccount>(
                                                                        "userAccountVState",
                                                                        TagUserAccount.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserAccount> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        String user_key = value.f1.getUser_key();
                                        int created_at = value.f1.getCreated_at();
                                        int updated_at = value.f1.getUpdated_at();

                                        TagUserAccount tmpState = userAccountVState.value();
                                        TagUserAccount curState =
                                                tmpState == null
                                                        ? TagUserAccount.init(uid)
                                                        : tmpState;

                                        if (curState.getUpdated_at() < updated_at) {
                                            if (!curState.getRegister_time().equals(created_at)
                                                    || !curState.getUser_key().equals(user_key)) {
                                                curState.register_time = created_at;
                                                curState.user_key = user_key;
                                                curState.updated_at = updated_at;

                                                JSONObject jsonObject = new JSONObject();
                                                jsonObject.put("uid", uid);
                                                jsonObject.put("user_key", user_key);
                                                jsonObject.put("register_time", created_at);

                                                out.collect(jsonObject.toString());
                                                userAccountVState.update(curState);
                                            }
                                        }
                                    }
                                });

        return out;
    }

    public int getUpdated_at() {
        return updated_at;
    }

    public long getUid() {
        return uid;
    }

    public String getUser_key() {
        return user_key;
    }

    public Integer getRegister_time() {
        return register_time;
    }

    @Override
    public String toString() {
        return "UserAccountTag{" + "uid=" + uid + ", register_time=" + register_time + '}';
    }
}
